﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.Web.Helpers;
using System.Threading.Tasks;

namespace Web.Controllers
{
    [NoCache]
    public class SecurityController : AsyncCommonControllerVersion2
    {
        //
        // GET: /Logon/

        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public ActionResult SingIn()
        {
            return View();
        }

        [HttpPost]
        public async Task<ActionResult> SingIn(string email = null, string password = null, string api_key = null)
        {
            var edex = (String.IsNullOrEmpty(api_key))
                ? new EdexApiClient.api.v2.EdexApiContext(email, password)
                : new EdexApiClient.api.v2.EdexApiContext(api_key);

            var user = await edex.GetSessionUser();
            var company = await edex.GetSessionCompany();

            Session.Timeout = 60;

            Session["api_key"] = edex.api_key;
            Session["user"] = user.GetValue();
            Session["company"] = company.GetValue();
            Session["company_name"] = company.GetValue() != null
                ? company.GetValue().COMPANY_NAME
                : "Компания не указана";

            /// Это удалить!!!!
            /// И перестроить все контроллеры
            Session["api_session"] = new EdexApiClient.EdexApiContext(edex.api_key).session;

            return RedirectToAction("Index", "Default");
        }

        [HttpGet]
        public async Task<ActionResult> SingOut()
        {
            await this.EdexContext.LogOut();

            Session.Clear();
            return RedirectToAction("Index", "Default");
        }

        [HttpPost]
        public async Task<ActionResult> Register(EdexApiClient.SEC_USERS user)
        {
            var private_key = System.Configuration.ConfigurationManager.AppSettings["CAPTCHA_PRIVATE_KEY"];
            if (!Microsoft.Web.Helpers.ReCaptcha.Validate(privateKey: private_key))
            {
                throw new Exception("Captcha validation failed");
            }

            var edex = new EdexApiClient.api.v2.EdexApiContext();
            await edex.Register(user);

            await this.SingIn(user.EMAIL, user.PASSWORD);
            return RedirectToAction("Index", "Default");
        }

        [HttpGet]
        public async Task<ActionResult> Profile()
        {
            var user = await this.EdexContext.GetSessionUser();
            return View(user.GetValue());
        }

        [HttpPost]
        public async Task<ActionResult> Profile(EdexApiClient.SEC_USERS user)
        {
            await this.EdexContext.ChangeUserInfo(user);

            /// Если указан новый пароль
            /// проверяем капчу и сохраняем
            if (!String.IsNullOrWhiteSpace(user.PASSWORD))
            {
                var private_key = System.Configuration.ConfigurationManager.AppSettings["CAPTCHA_PRIVATE_KEY"];

                if (!Microsoft.Web.Helpers.ReCaptcha.Validate(privateKey: private_key))
                {
                    throw new Exception("Captcha validation failed");
                }

                await this.EdexContext.ChangePassword(user.PASSWORD);
            }

            /// Если все ок - обновляем данные в сессии
            Session["user"] = user;

            return View("ProfileEditComplete");
        }

        [HttpGet]
        public async Task<ActionResult> ChangeCompany()
        {
            var user = await this.EdexContext.GetSessionUser();
            var data = await this.EdexContext.GetAllowedCompanies(user.GetValue().GUID_RECORD);
            return View(data.GetValues());
        }

        [HttpPost]
        public async Task<ActionResult> ChangeCompany(string company_key)
        {
            await this.EdexContext.ChangeSessionCompany(Guid.Parse(company_key));
            await this.SingIn(api_key: this.api_key);

            return RedirectToAction("Index", "Default");
        }

        [HttpPost]
        public async Task<ActionResult> PasswordReset(string email)
        {
            var private_key = System.Configuration.ConfigurationManager.AppSettings["CAPTCHA_PRIVATE_KEY"];
            if (!Microsoft.Web.Helpers.ReCaptcha.Validate(privateKey: private_key))
            {
                throw new Exception("Captcha validation failed");
            }

            var edex = new EdexApiClient.api.v2.EdexApiContext();

            await edex.ResetPassword(email);
            return View("PasswordResetComplete");
        }





        [HttpGet]
        public ActionResult Register()
        {
            return View();
        }

        [HttpGet]
        public ActionResult PasswordReset()
        {
            return View();
        }



    }
}
